<template>
    <page-layout>
        <template v-slot:header>
            <el-button type='success' size='small' @click="saveEvt">保存</el-button>
            <el-button size='small' @click="goback" >返回</el-button>
        </template>
        <el-form 
            :model="product" 
            :rules="rules" 
            label-width="100px" 
            size="small" 
            class="demo-ruleForm"
            ref="ruleForm"
            >
            <el-row>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="产品名字" prop="name">
                        <el-input v-model="product.name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="产品状态" >
                        <el-input value="新建" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="成本价" prop="pure_price">
                        <el-input v-model="product.pure_price"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="定价" prop="price">
                        <el-input v-model="product.price"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="优惠" prop="discount">
                        <el-input v-model="product.discount"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="限购" prop="limit">
                        <el-input v-model="product.limit"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="上架时间" prop="sale_stime">
                        <el-date-picker
                            v-model="product.sale_stime"
                            type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="下架时间" prop="sale_etime">
                        <el-date-picker
                            v-model="product.sale_etime"
                            type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="类型" prop="type">
                        <el-select v-model="product.type" placeholder="请选择产品类型">
                            <el-option v-for="it in options.type" 
                                :label="it.name" 
                                :value="it.code"
                                :key="it.code"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="单位" prop="unit">
                        <el-select  v-model="product.unit" placeholder="请选择产品单位">
                            <el-option v-for="it in options.unit" 
                                :label="it.name" 
                                :value="it.code"
                                :key="it.code"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="品级" prop="level">
                        <el-select v-model="product.level" placeholder="请选择产品品级">
                            <el-option v-for="it in options.level" 
                                :label="it.name" 
                                :value="it.code"
                                :key="it.code"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="产地" prop="place">
                        <el-input v-model="product.place"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="品牌" prop="brand">
                        <el-input v-model="product.brand"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24" >
                    <el-form-item label="详情" prop="detail">
                        <el-tag style="margin: 0 10px 10px 0;"
                            v-for="tag in product.detail"
                            :key="tag"
                            @close="closeEvt(tag, 'detail')"
                            closable>
                            {{tag}}
                        </el-tag>
                        <el-button size="small" @click="filePickEvt('detail')" icon='el-icon-upload2'/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="banner" prop="banner">
                        <el-tag style="margin: 0 10px 10px 0;"
                            v-for="tag in product.banner"
                            :key="tag"
                            @close="closeEvt(tag, 'banner')"
                            closable>
                            {{tag}}
                        </el-tag>
                        <el-button size="small" @click="filePickEvt('banner')" icon='el-icon-upload2'/>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" >
                    <el-form-item label="备注">
                        <el-input v-model="product.remark"></el-input>
                    </el-form-item>
                </el-col>
                <AddProduct v-model="product.list"  />
            </el-row>
        </el-form>    
    </page-layout>
</template>
<script>
    import AddProduct from "./AddProduct.vue";
    import { dictInfoApi,fileUploadApi,productAddApi } from "@/apis/productApi";
    import { filePicker } from "@/util/index";
    export default {
        components:{
            AddProduct
        },
        data(){
            return{
                product:{
                    "list": [
                    ],
                    "name": "",
                    "state": "new",
                    "pure_price": 0,
                    "price": 0,
                    "discount": 0,
                    "limit": 0,
                    "sale_stime": "",
                    "sale_etime": "",
                    "type": "",
                    "unit": "",
                    "level": "",
                    "place": "",
                    "brand": "",
                    "detail": [],
                    "banner": [],
                    "remark": ""
                },
                options:{
                    level:[],
                    unit:[],
                    type:[]
                },
                rules:{
                    name:[
                        { required: true, message: '请必须输入产品名字'},
                    ],
                    pure_price: [
                        {required: true, message: '成本价必须输入'},
                        {
                            validator:(_,value,cb)=>{
                                if(value*1 >= this.product.price * 1){
                                    cb(new Error('成本价不能高于定价'))
                                }else{
                                    cb()
                                }

                            }
                        }
                    ],
                    price: [
                        {required: true, message: '定价必须输入'},
                        {
                            validator:(_,value,cb)=>{
                                if(value * 1 <= this.product.pure_price * 1){
                                    cb(new Error('定价不能低于成本价'))
                                }else{
                                    cb()
                                }

                            }
                        }
                    ],
                    sale_stime: [
                        {required: true, message: '必须指定上架时间'},
                        {
                            validator:(_,value,cb)=>{
                                 if((Date.now() - 24 * 1000 * 60 * 60 ) > value.getTime()){
                                      cb(new Error('上架时间不能早于今天'))
                                  }else if((value.getTime() + 24*1000*60*60 ) > (new Date(this.product.sale_etime).getTime()) ){
                                      cb(new Error('上架时间不能比下架时间晚'))
                                  }else{
                                    cb()
                                  }
                            }
                        }
                    ],
                    sale_etime: [
                        {required: true, message: '必须指定下架时间'},
                        {
                            validator:(_,value,cb)=>{
                                  if(value.getTime() < (new Date(this.product.sale_stime).getTime() + 24*1000*60*60) ){
                                      cb(new Error('下架时间不能比上架时间早'))
                                  }else{
                                    cb()
                                  }
                            }
                        }
                    ],
                    discount: [
                        {required: true, message: '优惠价格必须数据'}
                    ],
                    limit: [
                        {required: true, message: '限购数量必须输入'}
                    ],
                    type: [
                        {trigger: 'change',required: true, message: '类型必须选择'}
                    ],
                    unit: [
                        {trigger: 'change',required: true, message: '单位必须选择'}
                    ],
                    level: [
                        {trigger: 'change',required: true, message: '品级必须选择'}
                    ],
                    place: [
                        {required: true, message: '产地必须输入'}
                    ],
                    brand: [
                        {required: true, message: '品牌必须输入'}
                    ],
                    detail: [
                        {required: true, message: '详情必须上传'}
                    ],
                    banner: [
                        {required: true, message: 'banner必须上传'}
                    ]
                }
                
            }
        },
        mounted(){
            // debugger
            Promise.all([
                dictInfoApi('UNITS'),
                dictInfoApi('MEDICAL'),
                dictInfoApi('PRODUCT_LEVEL')
            ]).then(d =>{
                if(d[0].code==200){
                    this.options.unit = d[0].data.rows
                    // console.log('this.options.unit',this.options.unit)
                }
                if(d[1].code==200){
                    this.options.type = d[1].data.rows
                }
                if(d[2].code==200){
                    this.options.level = d[2].data.rows
                }
                // console.log('d',d)
            })

        },
        methods:{
            saveEvt(){
                let _this = this
                // let sale_stime = "2023-01-04T16:00:00.000Z"
                // console.log(sale_stime.substring(0,10))
                let msg = ''
                if(this.product.list.length){
                    for(let i =0 ;i < this.product.list.length;i++){
                        if(this.product.list[i].count <= 0){
                             msg = `添加成分的第${i + 1}行的数量未填`
                             break
                        }
                        if(this.product.list[i].supplier_name == ''){
                             msg = `添加成分的第${i + 1}行的厂商未填`
                             break
                        }
                    }
                }
                if(msg){
                    this.$message.error(msg)
                    return
                }
                // this.$refs.ruleForm.validate(function (isOk , why) {
                //     console.log(isOk,why)
                // })
                this.$refs.ruleForm.validate().then(async()=>{
                    let arr = this.product
                    console.log('arr',arr)
                    // debugger
                    let result = await productAddApi({
                        ...arr,
                        banner:arr.banner.join('--'),
                        detail: arr.detail.join('--')
                    })
                    // let result = await productAddApi(arr)
                    if(result.code == 200){
                        this.$message.success('添加成功~')
                        console.log('result',result)
                    }else{
                        this.$message.error('添加失败！！')
                    }

                }).catch(()=>{
                    this.$message.error('未填充完数据或者填入的数据不符合规范！！')
                })

            },
            filePickEvt(type){
                filePicker((files)=>{
                    //把数据对象转为FormData对象
                   let formData = new FormData
                   Array(files.length).fill().map((_,i)=>{
                    //把文件数据循环传到formData中
                        formData.append('file',files[i])
                   })
                   fileUploadApi('product_'+type,formData).then(d=>{
                    // console.log('d',d)
                        if(d.code == 200){
                            this.product[type] = this.product[type].concat(
                                d.data.map(it => it.path)
                            )
                        }
                   })
                   
                    // console.log('files',files)
                })
            },
            closeEvt(tag,type){
                this.product[type].splice(this.product[type].findIndex(it=>it == tag),1)
            },
            goback(){
                this.$router.back()
            }
        }
    }
</script>
